import threading
import traceback
from concurrent.futures import ThreadPoolExecutor, as_completed


class Common:
    """通用类"""

    def __init__(self):
        super().__init__()

    def single_thread(self, func, *args, **kwargs):
        """单任务线程"""
        def _wrapper():
            try:
                func(*args, **kwargs)
            except Exception as e:
                traceback.print_exc()

        t = threading.Thread(target=_wrapper, daemon=True)
        t.start()
        return t

    def multi_thread(self, servers, func):
        """多任务线程池"""
        results = {}
        with ThreadPoolExecutor(max_workers=8) as executor:
            future_map = {executor.submit(func, s): s for s in servers}

            for future in as_completed(future_map):
                server = future_map[future]
                ip = server.get("ip", "unknown")
                try:
                    res = future.result()
                    results[ip] = res
                except Exception as e:
                    results[ip] = {
                        "status": False,
                        "stdout": "",
                        "stderr": "",
                        "error": str(e),
                        "msg":""
                    }
        return results

    def run_task(self, func, targets, on_finished=None):
        """统一任务执行"""
        def run():
            result = self.multi_thread(targets, func)
            if callable(on_finished):
                on_finished(result)

        self.single_thread(run)
